package state;

import java.awt.Point;
import java.util.ArrayList;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import javax.swing.JOptionPane;

import chesskers.GamePiece;

@SuppressWarnings("serial")
public class GameState implements java.io.Serializable{
	public GamePiece[][] board;
	
	public ArrayList<Point> moveTo;
	public ArrayList<Point> attackTo;
	public int selectedX;
	public int selectedY;
	public Profile player1;
	public Profile player2;
	public boolean blackGoing;
	public boolean isLoaded;
	public long timeLimit;
	
	public GameState(GamePiece[][] aBoard, 
			ArrayList<Point> aMoveTo, 
			ArrayList<Point> aAttackTo,
			int aSelectedX,
			int aSelectedY,
			boolean isBlackGoing,
			Profile aPlayer1,
			Profile aPlayer2)
	{
		board = aBoard;
		moveTo = aMoveTo;
		attackTo = aAttackTo;
		selectedX = aSelectedX;
		selectedY = aSelectedY;
		player1 = aPlayer1;
		player2 = aPlayer2;
		blackGoing = isBlackGoing;
	}

	public GameState() {
		board = null;
		moveTo = null;
		attackTo = null;
		selectedX = -1;
		selectedY = -1;
		player1 = null;
		player2 = null;
		blackGoing = false;
	}
	
	public void UpdateProfiles() {
		java.awt.EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				String profileFileName = "profiles.data";
				ArrayList<Profile> profilesList = new ArrayList<Profile>();
				try {
					FileInputStream fIn = new FileInputStream(profileFileName);
					if (fIn.available() != 0) {
						ObjectInputStream in = new ObjectInputStream(fIn);
						profilesList = (ArrayList<Profile>) in.readObject();
						in.close();
						fIn.close();
					} else {
						fIn.close();
					}
				} catch (IOException e) {
					JOptionPane.showMessageDialog(null, this, "Error updating profiles", selectedX);
					JOptionPane.showMessageDialog(null, this, e.toString(), selectedX);
				} catch (ClassNotFoundException ex) {
					JOptionPane.showMessageDialog(null, this, "Error 2 updating profiles", selectedX);
				}
		
				for (int i = 0; i < profilesList.size(); i++) {
					if (profilesList.get(i).name.equals(player1.name)) {
						profilesList.set(i, player1);
					} else if (profilesList.get(i).name.equals(player2.name)) {
						profilesList.set(i, player2);
					}
				}
		
				FileOutputStream fOut = null;
				ObjectOutputStream objOut = null;
		
				try {
					fOut = new FileOutputStream(profileFileName);
					objOut = new ObjectOutputStream(fOut);
					objOut.writeObject(profilesList);
					objOut.close();
				} catch (IOException e) {
					JOptionPane.showMessageDialog(null, this, "Error saving profiles", selectedX);
				}
			}
		});
	}
}
